/* eslint-disable react-hooks/exhaustive-deps */
/*
 * @Author: yzr
 * @Date: 2023-09-12 14:19:15
 * @LastEditors: qingyuanyang
 * @LastEditTime: 2023-10-10 14:25:16
 * @Description:
 * @FilePath: /utilization/src/components/PaginationSelf/index.tsx
 */
import React, {
  useEffect,
  useState,
  forwardRef,
  useImperativeHandle,
} from 'react';
import { Pagination } from 'antd';
import type { PaginationProps } from 'antd';

type selfProps = PaginationProps & {
  api?: (data?: any, options?: { [key: string]: any }) => Promise<any>;
  setTableData?: (data: any) => void;
  formData?: {
    [key: string]: any;
  };
};
export type PaginationRef = {
  getPageList: () => void;
};
const PaginationSelf: React.ForwardRefRenderFunction<
  PaginationRef,
  selfProps
> = ({ api, formData, setTableData, ...restProps }, ref) => {
  const [total, setTotal] = useState<number>();
  let defaultSize = restProps.defaultPageSize || 10;
  let defaultPage = restProps.defaultCurrent || 1;
  const [first, setFirst] = useState<boolean>(true);
  const [pageSize, setPageSize] = useState<number>(defaultSize);
  const [page, setPage] = useState<number>(defaultPage);
  useEffect(() => {
    // 首次不做处理
    if (first) {
      setFirst(false);
      return;
    }
    setPage(1);
    getPageList();
  }, [formData]);

  useEffect(() => {
    getPageList();
  }, [page, pageSize]);
  const getPageList = () => {
    if (api) {
      api({ ...formData, page, pageSize }).then(res => {
        setTotal(res?.data?.total);
        if (setTableData) {
          setTableData(res?.data);
        }
      });
    }
  };
  const changePageHandle = (currentPage: number, currentPageSize: number) => {
    setPage(currentPage);
    setPageSize(currentPageSize);
  };
  useImperativeHandle(ref, () => ({
    getPageList,
  }));
  if (total) {
    return (
      <>
        {total > 10 ? (
          <Pagination
            style={{ textAlign: 'right', marginTop: '20px' }}
            total={total}
            defaultPageSize={pageSize}
            {...restProps}
            hideOnSinglePage
            showSizeChanger
            showQuickJumper
            showTotal={total => `共 ${total} 条`}
            onChange={changePageHandle}
          />
        ) : (
          ''
        )}
      </>
    );
  }
  return <></>;
};
export default forwardRef(PaginationSelf);
